AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

include( 'shared.lua' )


function ENT:Initialize()
 
	self.Entity:SetModel( "models/weapons/w_eq_fraggrenade_thrown.mdl" )
	self.Entity:PhysicsInit( SOLID_VPHYSICS )      -- Make us work with physics,
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS )   -- after all, gmod is a physics
	self.Entity:SetSolid( SOLID_VPHYSICS )         -- Toolbox
 
        local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
	end
end
 
function ENT:Use( activator, caller )
    return
end

if SERVER then
	function ENT:Think()
		self.Entity.LastVel = self.Entity:GetVelocity()
		if self.Entity.StickW then
			self.Entity:StickWorld(self.Entity.StickW)
			self.Entity.StickW = nil
		end
		if self.Entity.Timer then
			if !timer.IsTimer("detonate"..self.Entity:EntIndex()) then
				timer.Create("detonate"..self.Entity:EntIndex(),self.Entity.Timer,1,function()
					local explode = ents.Create( "env_explosion" ) //creates the explosion
					explode:SetPos( self.Entity:GetPos() ) //this creates the explosion where you were looking
					explode:SetOwner( self.Entity.Owner ) // this sets you as the person who made the explosion
					explode:Spawn() //this actually spawns the explosion
					explode:SetKeyValue( "iMagnitude", "110" ) //the magnitude
					explode:Fire( "Explode", 0, 0 )
					explode:EmitSound( "weapon_AWP.Single", 400, 400 ) //the sound for the explosion, and how far away it can be heard
					timer.Remove("detonate"..self.Entity:EntIndex())
					self.Entity:Remove()
				end)
			end
		end
	end

	function ENT:PhysicsCollide(data,phys)
		if !self.Entity:GetParent():IsValid() and !data.HitEntity:IsWorld() and !constraint.HasConstraints(self.Entity) and !self.Entity.StickW then
			self.Entity:SetPos(self.Entity:GetPos()+self.Entity.LastVel:Normalize()*3)
			self.Entity:SetParent(data.HitEntity)
			if data.HitEntity:IsPlayer() then
				data.HitEntity.Stuck = self.Entity
			end
		elseif data.HitEntity:IsWorld() then
			phys:EnableMotion(false)
			self.Entity.StickW = data.HitEntity
		end
	end
end

function ENT:StickWorld(world)
	constraint.Weld(self.Entity,world,0,0,0,true)
end